{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Table A9 (Appendices)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loaded: jcr_mutiny_conflict_data.dta  |  Rows=1,599,624  Cols=94\n",
      "┌─ LAG / LEAD OLS LaTeX TABLE ─────────────────────────────────────────────\n",
      "\\begin{table}\n",
      "\\caption{}\n",
      "\\label{}\n",
      "\\begin{center}\n",
      "\\begin{tabular}{llll}\n",
      "\\hline\n",
      "                   & Mutiny + Lag & Mutiny + Lead & Mutiny + Lag \\& Lead  \\\\\n",
      "\\hline\n",
      "Military mutiny (t)          & 0.001***     & 0.001***      & 0.001***              \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "l\\_Military mutiny (t)       & 0.000*       &               & 0.000                 \\\\\n",
      "                   & (0.000)      &               & (0.000)               \\\\\n",
      "f\\_Military mutiny (t)       &              & 0.000         & 0.000                 \\\\\n",
      "                   &              & (0.000)       & (0.000)               \\\\\n",
      "Military spending per soldier (logged) & -0.000       & -0.000        & -0.000                \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Year since the last coup & 0.000***     & 0.000***      & 0.000***              \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Civil conflict  & 0.001***     & 0.001***      & 0.001***              \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Defense alliance    & -0.000*      & -0.000*       & -0.000*               \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Capability ratio            & 0.001***     & 0.001***      & 0.001***              \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Both democracy               & -0.000***    & -0.000**      & -0.000**              \\\\\n",
      "                   & (0.000)      & (0.000)       & (0.000)               \\\\\n",
      "Major power         & 0.005***     & 0.005***      & 0.005***              \\\\\n",
      "                   & (0.001)      & (0.001)       & (0.001)               \\\\\n",
      "Constant          & 0.003**      & 0.010***      & 0.003**               \\\\\n",
      "                   & (0.001)      & (0.002)       & (0.001)               \\\\\n",
      "R-squared          & 0.002        & 0.002         & 0.002                 \\\\\n",
      "R-squared Adj.     & 0.002        & 0.002         & 0.002                 \\\\\n",
      "N                  & 1314720      & 1309481       & 1286398               \\\\\n",
      "R²                 & 0.002        & 0.002         & 0.002                 \\\\\n",
      "Year Fixed Effects & \\checkmark & \\checkmark & \\checkmark \\\\\n",
      "Clustered SE (unit) & \\checkmark & \\checkmark & \\checkmark \\\\\n",
      "\\hline\n",
      "\\end{tabular}\n",
      "\\end{center}\n",
      "\\end{table}\n",
      "\\bigskip\n",
      "Standard errors in parentheses. \\newline \n",
      "* p<.1, ** p<.05, ***p<.01\n",
      "└──────────────────────────────────────────────────────────────────────────\n",
      "Saved lag/lead FE table to: C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\fe_table_laglead.tex\n"
     ]
    }
   ],
   "source": [
    "# --------------------------------------------------------\n",
    "# 0) Lightweight installer if packages are missing\n",
    "# --------------------------------------------------------\n",
    "\n",
    "try:\n",
    "    import pandas as _pd; import statsmodels as _sm; import matplotlib as _mpl\n",
    "except Exception:\n",
    "    import sys, subprocess\n",
    "    import subprocess\n",
    "    subprocess.check_call(\n",
    "        [sys.executable, \"-m\", \"pip\", \"install\", \"-U\",\n",
    "         \"pandas\", \"statsmodels\", \"matplotlib\"]\n",
    "    )\n",
    "\n",
    "from pathlib import Path\n",
    "import pandas as pd\n",
    "import statsmodels.formula.api as smf\n",
    "from statsmodels.iolib.summary2 import summary_col\n",
    "import matplotlib.pyplot as plt\n",
    "import os\n",
    "\n",
    "\n",
    "# ----------------------------\n",
    "# 1) Load data\n",
    "# ----------------------------\n",
    "file_path = Path(\n",
    "    r\"C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\jcr_mutiny_conflict_data.dta\"\n",
    ")\n",
    "if not file_path.exists():\n",
    "    raise FileNotFoundError(f\"Could not find .dta file at: {file_path}\")\n",
    "\n",
    "data = pd.read_stata(file_path)\n",
    "print(f\"Loaded: {file_path.name}  |  Rows={len(data):,}  Cols={len(data.columns)}\")\n",
    "\n",
    "# ----------------------------\n",
    "# 2) Create lag and lead of mutiny\n",
    "# ----------------------------\n",
    "# Sort by panel id and year\n",
    "data = data.sort_values(['id', 'year'])\n",
    "\n",
    "# Lag (t-1) and Lead (t+1) of mutiny_t\n",
    "data['l_mutiny_t'] = data.groupby('id')['mutiny_t'].shift(1)\n",
    "data['f_mutiny_t'] = data.groupby('id')['mutiny_t'].shift(-1)\n",
    "\n",
    "\n",
    "# --------------------------------------------------------------\n",
    "# 3) Estimate models with lag/lead\n",
    "#    Note: outcome is \"dispute\" (change to dispute2 if needed)\n",
    "# --------------------------------------------------------------\n",
    "\n",
    "# Common controls\n",
    "control_vars = [\n",
    "    'lmmilex_persol_t', 'years_since_coup', 'ucdp_civconf_t2',\n",
    "    'defense_target', 'capprop', 'jdem', 'majorpower', 'year', 'id'\n",
    "]\n",
    "\n",
    "# --- Model 1: mutiny_t + lag ---\n",
    "model1_subset = ['mutiny_t', 'l_mutiny_t'] + control_vars\n",
    "model1_data = data.dropna(subset=model1_subset)\n",
    "\n",
    "model1 = smf.ols(\n",
    "    'dispute ~ mutiny_t + l_mutiny_t + lmmilex_persol_t + years_since_coup + '\n",
    "    'ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)',\n",
    "    data=model1_data\n",
    ").fit(cov_type='cluster', cov_kwds={'groups': model1_data['id']})\n",
    "\n",
    "# --- Model 2: mutiny_t + lead ---\n",
    "model2_subset = ['mutiny_t', 'f_mutiny_t'] + control_vars\n",
    "model2_data = data.dropna(subset=model2_subset)\n",
    "\n",
    "model2 = smf.ols(\n",
    "    'dispute ~ mutiny_t + f_mutiny_t + lmmilex_persol_t + years_since_coup + '\n",
    "    'ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)',\n",
    "    data=model2_data\n",
    ").fit(cov_type='cluster', cov_kwds={'groups': model2_data['id']})\n",
    "\n",
    "# --- Model 3: mutiny_t + lag + lead ---\n",
    "model3_subset = ['mutiny_t', 'l_mutiny_t', 'f_mutiny_t'] + control_vars\n",
    "model3_data = data.dropna(subset=model3_subset)\n",
    "\n",
    "model3 = smf.ols(\n",
    "    'dispute ~ mutiny_t + l_mutiny_t + f_mutiny_t + lmmilex_persol_t + years_since_coup + '\n",
    "    'ucdp_civconf_t2 + defense_target + capprop + jdem + majorpower + C(year)',\n",
    "    data=model3_data\n",
    ").fit(cov_type='cluster', cov_kwds={'groups': model3_data['id']})\n",
    "\n",
    "\n",
    "# ----------------------------\n",
    "# 4) Build LaTeX table \n",
    "# ----------------------------\n",
    "\n",
    "regressor_order = [\n",
    "    'mutiny_t',\n",
    "    'l_mutiny_t',\n",
    "    'f_mutiny_t',\n",
    "    'lmmilex_persol_t',\n",
    "    'years_since_coup',\n",
    "    'ucdp_civconf_t2',\n",
    "    'defense_target',\n",
    "    'capprop',\n",
    "    'jdem',\n",
    "    'majorpower',\n",
    "    'Intercept'\n",
    "]\n",
    "\n",
    "info_dict = {\n",
    "    'N':  lambda x: f\"{int(x.nobs)}\",\n",
    "    'R²': lambda x: f\"{x.rsquared:.3f}\"\n",
    "}\n",
    "\n",
    "table = summary_col(\n",
    "    results=[model1, model2, model3],\n",
    "    float_format='%0.3f',\n",
    "    stars=True,\n",
    "    model_names=['Mutiny + Lag', 'Mutiny + Lead', 'Mutiny + Lag & Lead'],\n",
    "    info_dict=info_dict,\n",
    "    drop_omitted=True,\n",
    "    regressor_order=regressor_order\n",
    ")\n",
    "\n",
    "latex_lines = table.as_latex().splitlines()\n",
    "\n",
    "# Insert Year FE & clustered SE rows just under R²\n",
    "for i, line in enumerate(latex_lines):\n",
    "    if 'R²' in line:\n",
    "        latex_lines.insert(\n",
    "            i + 1,\n",
    "            r'Year Fixed Effects & \\checkmark & \\checkmark & \\checkmark \\\\'\n",
    "        )\n",
    "        latex_lines.insert(\n",
    "            i + 2,\n",
    "            r'Clustered SE (unit) & \\checkmark & \\checkmark & \\checkmark \\\\'\n",
    "        )\n",
    "        break\n",
    "\n",
    "# Remove explicit C(year) coefficient rows, keep only checkmark row\n",
    "filtered_lines = [\n",
    "    line for line in latex_lines\n",
    "    if 'C(year)' not in line\n",
    "]\n",
    "\n",
    "# Clean variable labels\n",
    "replacements = {\n",
    "    'mutiny\\\\_t': 'Military mutiny (t)',\n",
    "    'l\\\\_mutiny\\\\_t': 'Military mutiny (t-1)',\n",
    "    'f\\\\_mutiny\\\\_t': 'Military mutiny (t+1)',\n",
    "    'lmmilex\\\\_persol\\\\_t': 'Military spending per soldier (logged)',\n",
    "    'years\\\\_since\\\\_coup': 'Year since the last coup',\n",
    "    'ucdp\\\\_civconf\\\\_t2': 'Civil conflict',\n",
    "    'defense\\\\_target': 'Defense alliance',\n",
    "    'capprop': 'Capability ratio',\n",
    "    'jdem': 'Both democracy',\n",
    "    'majorpower': 'Major power',\n",
    "    'Intercept': 'Constant',\n",
    "    'const': 'Constant'\n",
    "}\n",
    "\n",
    "fixed_lines = []\n",
    "for line in filtered_lines:\n",
    "    for old, new in replacements.items():\n",
    "        line = line.replace(old, new)\n",
    "    fixed_lines.append(line)\n",
    "\n",
    "custom_latex = '\\n'.join(fixed_lines)\n",
    "\n",
    "\n",
    "# ----------------------------\n",
    "# 5) Print and save LaTeX\n",
    "# ----------------------------\n",
    "print(\"┌─ LAG / LEAD OLS LaTeX TABLE ─────────────────────────────────────────────\")\n",
    "for l in custom_latex.split(\"\\n\"):\n",
    "    print(l)\n",
    "print(\"└──────────────────────────────────────────────────────────────────────────\")\n",
    "\n",
    "output_path = r\"C:\\Users\\rmuhi\\OneDrive\\Desktop\\Mutiny_Conflict Paper_All\\Replication File\\table_A9.tex\"\n",
    "with open(output_path, \"w\", encoding=\"utf-8\") as f:\n",
    "    f.write(custom_latex)\n",
    "\n",
    "print(\"Saved lag/lead FE table to:\", output_path)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.13.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
